package com.awenhui.demo.config.feign.strategy.safety;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.awenhui.demo.config.feign.strategy.safety.ISafetyStrategy;
import com.awenhui.demo.config.properties.GyfcProperty;
import feign.RequestTemplate;
import feign.Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;



/**
 * 贵阳房房产签名策略
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/7/2 17:15
 */
@Slf4j
@Component("gyfcSignStrategyImpl")
public class GyfcSignStrategyImpl implements ISafetyStrategy {
    private final GyfcProperty gyfcProperty;

    @Autowired
    public GyfcSignStrategyImpl(GyfcProperty gyfcProperty) {
        this.gyfcProperty = gyfcProperty;
    }


    @Override
    public void handleSafety(RequestTemplate template) {
        String method = template.method();
        if ("POST".equalsIgnoreCase(method)) {
            handlePost(template);
        } else if ("GET".equalsIgnoreCase(method)) {
            handleGet(template);
        }
    }


    /**
     * 处理post请求加签
     *
     * @param template ${@link RequestTemplate}
     * @author zhouxuanhong
     * @date 2019-06-14 13:57
     */
    private void handlePost(RequestTemplate template) {
        byte[] body = template.body();
        if (body.length > 0) {
            String bodyStr = new String(body, Util.UTF_8);
            if (StringUtils.isNotBlank(bodyStr)) {
                // 数据处理
                JSONObject jsonObject = JSON.parseObject(bodyStr);
                String timestamp = System.currentTimeMillis() + "";
                String nonceStr = UUID.randomUUID().toString().substring(0, 8);
                String sign = getSign(nonceStr, timestamp);
                jsonObject.put("sign", sign);
                jsonObject.put("noncestr", nonceStr);
                jsonObject.put("timestamp", timestamp);
                jsonObject.put("appid", gyfcProperty.getAppId());
                body = JSONObject.toJSONString(jsonObject).getBytes(Util.UTF_8);
            }
        }

        // 重置请求体参数
        template.body(body, Util.UTF_8);
    }


    /**
     * 处理get请求加签
     *
     * @param template ${@link RequestTemplate}
     * @author zhouxuanhong
     * @date 2019-06-14 13:57
     */
    private void handleGet(RequestTemplate template) {
        Map<String, Collection<String>> queries = new LinkedHashMap<>(template.queries());
        // 签名用的appId
        List<String> appId = new ArrayList<>();
        appId.add(gyfcProperty.getAppId());
        queries.put("appid", appId);

        // 生成签名数据
        String timestamp = System.currentTimeMillis() + "";
        String nonceStr = UUID.randomUUID().toString().substring(0, 8);
        String sign = getSign(nonceStr, timestamp);
        queries.put("sign", Arrays.asList(sign));

        // 签名用的nonceStr
        queries.put("noncestr",Arrays.asList(nonceStr) );

        // 签名用的timestamp
        queries.put("timestamp",Arrays.asList(timestamp));

        // 重置请求地址参数
        template.queries(null);
        template.queries(queries);
    }


    /**
     * 获取签名sign
     *
     * @param nonceStr  ${@link String}
     * @param timestamp ${@link String}
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-06-18 20:05
     */
    private String getSign(String nonceStr, String timestamp) {
        StringBuilder sb = new StringBuilder();
        sb.append("appid=").append(gyfcProperty.getAppId())
                .append("&noncestr=").append(nonceStr)
                .append("&timestamp=").append(timestamp)
                .append("&key=").append(gyfcProperty.getKey());
        return DigestUtils.md5Hex(sb.toString());
    }
}
